package com.zdth.wxpush.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zdth.wxpush.config.WxConfig;
import com.zdth.wxpush.model.Constellation;
import com.zdth.wxpush.model.R;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

/**
 * @Author Z-7
 * @Date 2022/8/29
 */
@Component
@Slf4j
public class WxPushUtil {

    @Value("${file.picPath}")
    private String picPath;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private ApiUtil apiUtil;
    @Resource
    private WxConfig wxConfig;

    private String getAccessToken() {
        String message = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppID() + "&secret=" + wxConfig.getAppsecret());
        JSONObject entries = JSONUtil.parseObj(message);
        String accessToken = entries.getStr("access_token");
        return accessToken;
    }

    public void sendOther(String user,Integer day) throws WxErrorException {
        WxMpTemplateMessage templateMessage = getTemplate(user, day);

        R weather = apiUtil.getOtherWeather(day, "广东");
        send(templateMessage, weather, day);
    }

    /**
     * {{time.DATA}}
     * {{province.DATA}}-{{city.DATA}}
     * 今日天气：{{info.DATA}}
     * 最高温度：{{maxTemp.DATA}}
     * 最低温度：{{minTemp.DATA}}
     * 风力情况：{{direct.DATA}}，{{power.DATA}}
     *
     * @throws WxErrorException
     */
    public void sendMessage(String user,Integer day) throws WxErrorException {
        WxMpTemplateMessage templateMessage = getTemplate(user, day);

        R weather = apiUtil.getWeather(day, "浦东");
        send(templateMessage, weather, day);
    }

    public void sendToGaoLing(String user,Integer day) throws WxErrorException {
        WxMpTemplateMessage templateMessage = getTemplate(user, day);

        R weather = apiUtil.getWeather(day, "松江");
        send(templateMessage, weather, day);
    }

    /**
     * {{date.DATA}} {{topSearch.DATA}}
     *
     * @throws WxErrorException
     */
    public void sendTopSearch() throws WxErrorException {
        WxMpTemplateMessage templateMessage = getTemplate("odJas5_9M6pEpAWw4TeTP-xaOnWg", -1);

        R r = apiUtil.getTopSearch();
        sendTopSearch(templateMessage, r);
    }

    /**
     * {{message.DATA}}
     *
     * @throws WxErrorException
     */
    public void sendDog(String user) throws WxErrorException {
        WxMpTemplateMessage templateMessage = getTemplate(user, 0);

        String message = apiUtil.getDog();
        sendDog(templateMessage,message);
    }

    /**
     * 星座
     * @param user 用户
     * @param name 星座名称
     * @throws WxErrorException
     */
    public void sendXingZuo(String user,String name) throws WxErrorException {
        WxMpTemplateMessage templateMessage = getTemplate(user, 3);

        Constellation constellation = apiUtil.getConstellation(name);
        String linKing = apiUtil.getLinKing();
        constellation.setLinKing(linKing);
        sendXingZuo(templateMessage,constellation);
    }

    private void sendXingZuo(WxMpTemplateMessage templateMessage,Constellation constellation) throws WxErrorException {
        templateMessage.addData(new WxMpTemplateData("title", constellation.getTitle(), "#87CEFA"));
        templateMessage.addData(new WxMpTemplateData("date", DateUtil.today(), "#DB7093"));
        templateMessage.addData(new WxMpTemplateData("allFortuneNum", constellation.getAllFortuneNum(), "#8A2BE2"));
        templateMessage.addData(new WxMpTemplateData("loveFortuneNum", constellation.getLoveFortuneNum(), "#8A2BE2"));
        templateMessage.addData(new WxMpTemplateData("workFortuneNum", constellation.getWorkFortuneNum(), "#8A2BE2"));
        templateMessage.addData(new WxMpTemplateData("moneyFortuneNum", constellation.getMoneyFortuneNum(), "#8A2BE2"));
        templateMessage.addData(new WxMpTemplateData("luckyColor", constellation.getLuckyColor(), "#800080"));
        templateMessage.addData(new WxMpTemplateData("luckyNumber", constellation.getLuckyNumber(), "#800080"));
        templateMessage.addData(new WxMpTemplateData("luckyConstellation", constellation.getLuckyConstellation(), "#800080"));
        templateMessage.addData(new WxMpTemplateData("allFortune", constellation.getAllFortune(), "#DEB887"));
        templateMessage.addData(new WxMpTemplateData("loveFortune", constellation.getLoveFortune(), "#DEB887"));
        templateMessage.addData(new WxMpTemplateData("workFortune", constellation.getWorkFortune(), "#DEB887"));
        templateMessage.addData(new WxMpTemplateData("moneyFortune", constellation.getMoneyFortune(), "#DEB887"));
        templateMessage.addData(new WxMpTemplateData("healthFortune", constellation.getHealthFortune(), "#DEB887"));
        templateMessage.addData(new WxMpTemplateData("shortComment", constellation.getShortComment(), "#000000"));
        templateMessage.addData(new WxMpTemplateData("linKing", constellation.getLinKing(), "#7FFFD4"));
        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    private void sendDog(WxMpTemplateMessage templateMessage,String message) throws WxErrorException {
        templateMessage.addData(new WxMpTemplateData("message", message, "#228B22"));
        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    private void send(WxMpTemplateMessage templateMessage, R weather, Integer day) throws WxErrorException {
        if (day == 7) {
            sendWeather(templateMessage, weather);
        } else if (day == 8) {
            String linKing = apiUtil.getLinKing();
            sendForecastWeather(templateMessage, weather.setLinKing(linKing));
        }
    }

    private void sendTopSearch(WxMpTemplateMessage templateMessage, R r) throws WxErrorException {
        templateMessage.addData(new WxMpTemplateData("date", DateUtil.now(), "#DB7093"));
        templateMessage.addData(new WxMpTemplateData("topSearch", r.getTopSearch(), "#173177"));
        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    private void sendWeather(WxMpTemplateMessage templateMessage, R weather) throws WxErrorException {
        templateMessage.addData(new WxMpTemplateData("time", DateUtil.now(), "#DB7093"));
        templateMessage.addData(new WxMpTemplateData("province", weather.getProvince(), "#173177"));
        templateMessage.addData(new WxMpTemplateData("city", weather.getCity(), "#173177"));
        templateMessage.addData(new WxMpTemplateData("info", weather.getInfo(), "#AFEEEE"));
        templateMessage.addData(new WxMpTemplateData("maxTemp", weather.getMaxTemp(), "#FA8072"));
        templateMessage.addData(new WxMpTemplateData("minTemp", weather.getMinTemp(), "#FFDAB9"));
        templateMessage.addData(new WxMpTemplateData("direct", weather.getDirect(), "#B0E0E6"));
        templateMessage.addData(new WxMpTemplateData("power", weather.getPower(), "#B0C4DE"));
        templateMessage.addData(new WxMpTemplateData("tips", weather.getTips(), "#6B8E23"));

        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    /**
     * 天气预报
     *
     * @param templateMessage
     * @param weather
     * @throws WxErrorException
     */
    private void sendForecastWeather(WxMpTemplateMessage templateMessage, R weather) throws WxErrorException {
        templateMessage.addData(new WxMpTemplateData("time", DateUtil.now(), "#DB7093"));
        templateMessage.addData(new WxMpTemplateData("province", weather.getProvince(), "#173177"));
        templateMessage.addData(new WxMpTemplateData("city", weather.getCity(), "#173177"));
        templateMessage.addData(new WxMpTemplateData("info", weather.getInfo(), "#AFEEEE"));
        templateMessage.addData(new WxMpTemplateData("maxTemp", weather.getMaxTemp(), "#FA8072"));
        templateMessage.addData(new WxMpTemplateData("minTemp", weather.getMinTemp(), "#FFDAB9"));
        templateMessage.addData(new WxMpTemplateData("direct", weather.getDirect(), "#B0E0E6"));
        templateMessage.addData(new WxMpTemplateData("power", weather.getPower(), "#B0C4DE"));
        templateMessage.addData(new WxMpTemplateData("linKing", weather.getLinKing(), "#8FBC8F"));
        templateMessage.addData(new WxMpTemplateData("tips", weather.getTips(), "#6B8E23"));

        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    private WxMpTemplateMessage getTemplate(String user, Integer day) {
        WxMpTemplateMessage templateMessage = null;
        if (day == 7) {
            // 今日天气
            templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user)
                    .templateId(wxConfig.getWeatherTemplate())
                    .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken())
                    .build();
        } else if (day == 8) {
            // 天气预报
            templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user)
                    .templateId(wxConfig.getForecastTemplate())
                    .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken())
                    .build();
        } else if (day == -1) {
            // 热搜
            templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user)
                    .templateId(wxConfig.getTopSearchTemplate())
                    .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken())
                    .build();
        } else if (day == 0) {
            // 舔狗日记
            templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user)
                    .templateId(wxConfig.getDogTemplate())
                    .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken())
                    .build();
        } else if (day == 3) {
            // 星座
            templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user)
                    .templateId(wxConfig.getConstellationTemplate())
                    .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken())
                    .build();
        }

        return templateMessage;
    }

    /**
     * 发送《买家秀》
     *
     * @param user
     * @throws WxErrorException
     */
    public void sendPic(String user) throws WxErrorException {
        File localFile = apiUtil.getPic();

        sendImage(localFile, user);
    }

    /**
     * 发送摸鱼日历
     */
    public void sendMoYuPic(String user) throws WxErrorException {
        File moYu = apiUtil.getMoYu();
        sendImage(moYu, user);
    }

    private void sendImage(File image, String user) throws WxErrorException {
        WxMediaUploadResult res = wxMpService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, image);

        WxMpKefuMessage build = WxMpKefuMessage
                .IMAGE()
                .toUser(user)
                .mediaId(res.getMediaId())
                .build();
        boolean result = wxMpService.getKefuService().sendKefuMessage(build);
        if (!result) {
            log.error(DateUtil.now() + "发送图片失败");
        }
    }
}
